package com.zhb.blog.web;


import com.zhb.blog.model.Blog;
import com.zhb.blog.service.BlogService;
import com.zhb.blog.service.TagService;
import com.zhb.blog.service.TypeService;
import com.zhb.blog.util.JsoupReptileUtil;
import com.zhb.blog.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;

    @GetMapping("/")
    public String index(Model model, @PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable){
        model.addAttribute("page",blogService.listBlog(pageable));//传过去的page每页只倒序按照更新时间展示5条
        model.addAttribute("types",typeService.listTypeTop(6));//展示6条分类
        model.addAttribute("tags",tagService.listTagTop(10));//展示10条标签
        model.addAttribute("recommendBlogs",blogService.listRecommendBlogTop(5));//展示5条推荐博客
        return "index";
    }
    @PostMapping("/search")
    public String search(Model model, @PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable, @RequestParam String query){
        model.addAttribute("page",blogService.listBlog("%"+query+"%",pageable));
        model.addAttribute("query",query);
        return "search";
    }
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model) throws IOException {
        Blog blog = blogService.getAndConvert(id);
        Map<String, String> blogs = JsoupReptileUtil.searchBlogs(blog.getTags());
        model.addAttribute("blog",blog);
        model.addAttribute("externalBlogs",blogs);
        return "blog";
    }

    @GetMapping("/footer/newblog")
    public String newBlogs(Model model){
        model.addAttribute("poem","床前明月光");
        return "_fragments :: newPoem";
    }
}
